package com.ruoyi.knowledge.task;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.knowledge.article.mapper.ArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class ArticleDataSyncTask {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleMapper articleMapper;


    @Scheduled(cron = "0 0/5 * * * ?") // 每5分钟执行一次
    public void syncArticleDataToDB() {
        // 同步点赞数
        Set<String> likeKeys = (Set<String>) redisCache.keys("article:like:*");
        for (String key : likeKeys) {
            if (!key.contains("user")) { // 过滤掉存用户ID的key
                Long articleId = Long.valueOf(key.split(":")[2]);
                Integer likeCount = redisCache.getCacheObject(key);
                if (likeCount != null && likeCount > 0) {
                    articleMapper.updateLikeCount(articleId, likeCount);
                    redisCache.deleteObject(key); // 同步后清除Redis记录
                }
            }
        }

        // 同步收藏数
        Set<String> collectKeys = (Set<String>) redisCache.keys("article:collect:*");
        for (String key : collectKeys) {
            if (!key.contains("user")) {
                Long articleId = Long.valueOf(key.split(":")[2]);
                Integer collectCount = redisCache.getCacheObject(key);
                if (collectCount != null && collectCount > 0) {
                    articleMapper.updateCollectCount(articleId, collectCount);
                    redisCache.deleteObject(key);
                }
            }
        }
    }
}